package ru.averta.notes.domain.forms;

import org.hibernate.validator.constraints.*;

import ru.averta.notes.domain.User;
import ru.averta.notes.service.security.login.UserPasswordEncoder;

import javax.validation.constraints.AssertTrue;

public class UserForm implements IFormToDomainObject<User> {

    @NotBlank()
    @Email
    @Length(max = 50)
    private String mail;
    @NotBlank
    @Length(max = 30)
    private String password;
    @NotBlank
    private String verifyPassword;
    private boolean isAdmin;

    public UserForm(){}
    public UserForm(User user){loadFromDomainObject(user);}

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail.toLowerCase();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getVerifyPassword() {
        return verifyPassword;
    }

    public void setVerifyPassword(String verifyPassword) {
        this.verifyPassword = verifyPassword;
    }

    public void setAdmin(boolean isAdmin) {
        this.isAdmin = isAdmin;
    }

    public boolean isAdmin() {
        return isAdmin;
    }

    public void hashPassword() {
        this.password = UserPasswordEncoder.hashPassword(password);
        this.verifyPassword = UserPasswordEncoder.hashPassword(verifyPassword);
    }

    @AssertTrue(message = "passVerify field should be equal than pass field")
    public boolean isPasswordSame() {
        return password.equals(verifyPassword);
    }

    public String toString() {
        return "Пользователь " + mail;
    }

    public void loadFromDomainObject(User object) {
        this.mail = object.getMail();
        this.password = object.getPassword();
        this.verifyPassword = object.getPassword();
        this.isAdmin = object.isAdmin();
    }

    public User loadToDomainObject(User object) {
        object.setMail(mail);
        object.setPassword(password);
        object.setAdmin(isAdmin);
        return object;
    }
}
